#!/usr/bin/env python3
"""
设备控制功能演示
"""

import asyncio
import httpx
import json


async def demo_control_devices():
    """演示设备控制功能"""
    
    print("🔧 IoT MCP 设备控制功能演示")
    print("=" * 50)
    
    # 演示关闭运行中的照明设备
    print("\n📋 演示: 关闭运行中的照明设备")
    print("-" * 30)
    
    control_data = {
        "device_nos": [
            "20250822-A411-100",  # 411-照明-3
            "20250822-A411-101",  # 411-照明-2
            "20250822-A411-102"   # 411-照明-1
        ],
        "state": "关闭"
    }
    
    print(f"控制数据: {json.dumps(control_data, indent=2, ensure_ascii=False)}")
    
    try:
        async with httpx.AsyncClient(timeout=15.0) as client:
            response = await client.post(
                "http://localhost:8000/api/devices/control",
                json=control_data,
                headers={"Content-Type": "application/json"}
            )
            
            if response.status_code == 200:
                data = response.json()
                print(f"\n✅ 控制成功!")
                print(f"消息: {data['message']}")
                print(f"总计: {data['summary']['total']} 个设备")
                print(f"成功: {data['summary']['success']} 个")
                print(f"失败: {data['summary']['failed']} 个")
                
                print("\n详细结果:")
                for result in data['results']:
                    print(f"  {result}")
                    
            else:
                print(f"\n❌ 控制失败!")
                print(f"状态码: {response.status_code}")
                print(f"错误: {response.text}")
                
    except httpx.ConnectError:
        print("\n❌ 连接失败: 请确保服务正在运行 (http://localhost:8000)")
        print("   启动服务: python main.py")
    except Exception as e:
        print(f"\n❌ 其他错误: {e}")


def show_api_info():
    """显示 API 信息"""
    print("\n📚 设备控制 API 信息")
    print("=" * 50)
    print("端点: POST /api/devices/control")
    print("功能: 控制指定设备的状态")
    
    print("\n请求体格式:")
    print("  {")
    print('    "device_nos": ["设备编号1", "设备编号2"],')
    print('    "state": "目标状态"')
    print("  }")
    
    print("\n支持的状态值:")
    print("  ✅ 开启: 运行中、开启、开")
    print("  ❌ 关闭: 断电、关闭、关")
    
    print("\n使用示例:")
    print("  # 关闭设备")
    print('  curl -X POST http://localhost:8000/api/devices/control \\')
    print('       -H "Content-Type: application/json" \\')
    print('       -d \'{"device_nos": ["20250822-A411-100"], "state": "关闭"}\'')
    
    print("\n  # 开启设备")
    print('  curl -X POST http://localhost:8000/api/devices/control \\')
    print('       -H "Content-Type: application/json" \\')
    print('       -d \'{"device_nos": ["20250822-A411-100"], "state": "开启"}\'')


async def main():
    """主函数"""
    try:
        # 演示设备控制
        await demo_control_devices()
        
        # 显示 API 信息
        show_api_info()
        
        print("\n🎉 演示完成!")
        print("\n💡 提示:")
        print("   - 确保服务正在运行: python main.py")
        print("   - 运行完整测试: python test_device_control.py")
        print("   - 查看 API 文档: http://localhost:8000/docs")
        
    except KeyboardInterrupt:
        print("\n\n⏹️ 演示被用户中断")
    except Exception as e:
        print(f"\n❌ 演示过程中发生错误: {e}")


if __name__ == "__main__":
    asyncio.run(main())
